package com.netease.nie.base.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * 
 * 文本压缩
 * 
 */
public class GZipUtils {

	/**
	 * 压缩
	 * 
	 * @param text
	 * @return
	 */
	public static String compress(String text) {

		try {
			byte[] stream = text.getBytes("utf-8");
			ByteArrayOutputStream out = new ByteArrayOutputStream(stream.length);
			GZIPOutputStream gzip = new GZIPOutputStream(out);
			try {
				gzip.write(stream);
			} finally {
				gzip.close();
			}
			return new sun.misc.BASE64Encoder().encode(out.toByteArray());
		} catch (IOException e) {
			return null;
		}
	}

	/**
	 * 解压缩
	 * 
	 * @param text
	 * @return
	 */
	public static String decompress(String text) {
		try {
			byte[] stream = new sun.misc.BASE64Decoder().decodeBuffer(text);
			ByteArrayInputStream in = new ByteArrayInputStream(stream);
			GZIPInputStream gzip = new GZIPInputStream(in);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			try {
				byte[] buffer = new byte[4 * 1024];
				int len = 0;
				while ((len = gzip.read(buffer)) != -1) {
					out.write(buffer, 0, len);
				}
			} finally {
				gzip.close();
			}
			return new String(out.toByteArray(), "utf-8");
		} catch (IOException e) {
			return null;
		}
	}
}